from django.shortcuts import render, get_object_or_404, HttpResponse
from django.utils.safestring import mark_safe
# from django.http import FileResponse
from .v1 import StarkConfig
from django.conf.urls import url


class UploadConfig(object):
    """
    def display_upload(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '上传图片'
        reset_url = self.reverse_commons_url(self.get_url_name('upload'), pk=obj.pk)
        return mark_safe("<a href='%s'>上传图片</a>" % reset_url)
    
    def upload_view(self, request, pk, *args, **kwargs):
        current_change_object = self.get_change_object(request, pk, *args, **kwargs)
        if not current_change_object:
            return HttpResponse('要上传图片的房屋不存在，请重新选择！')
        # 上传文件和展示文件列表
        model_form_class = self.get_img_form_class(False, request, pk, *args, **kwargs)
        if request.method == 'GET':
            form = model_form_class(instance=current_change_object)
            return render(request, 'stark/upload_img.html', {'form': form})

        if request.method == 'POST':
            form = model_form_class
            if form.is_valid():
                # 获取上传的文件对象
                uploaded_file = request.FILES['file']
                # 保存到数据库（文件名使用原始文件名）
                StarkConfig.model_class.objects.create(
                    file_name=uploaded_file.name,
                    file=uploaded_file
                )
                return redirect('file_list')  # 重定向刷新页面
        else:
            form = model_form_class()

        # 获取所有文件，按上传时间倒序排列
        files = FileModel.objects.all().order_by('-upload_time')
        return render(request, 'file_list.html', {'form': form, 'files': files})

    # 下载文件
    def fdownload_view(request, file_id):
        file_obj = get_object_or_404(FileModel, id=file_id)
        # 打开文件并返回给用户（as_attachment=True 强制下载）
        response = FileResponse(file_obj.file.open(), as_attachment=True)
        # 设置下载的文件名（与原始文件名一致）
        response['Content-Disposition'] = f'attachment; filename="{file_obj.file_name}"'
        return response

    
    def extra_urls(self):
        patterns = [
            url(r'^upload/(?P<pk>\d+)/$', self.wrapper(self.upload_view),
                name=self.get_url_name('upload')),
        ]
        return patterns
    """
    pass

